package com.android.hitch.network;

import java.io.IOException;
import java.util.*;

public class Connection extends AbstractClient {
	List<HandlerClientIF> handlList;
	
	public Connection (String host, int port) {
		super(host, port);
		handlList = new ArrayList<HandlerClientIF>();
	}	
	
	public void Connect() {
		try {
			this.openConnection();
		} catch (IOException e) {
			e.printStackTrace();
			Iterator<HandlerClientIF> itr = handlList.iterator();
			while(itr.hasNext()) {
				HandlerClientIF handle = (HandlerClientIF) itr.next();
				handle.OnConnectingException(e);
			}	
		}
	}
	
	public void AddHandler(HandlerClientIF handler) {
		if (!handlList.contains(handler))
			handlList.add(handler);
	}
	
	public void removeHandler(HandlerClientIF handler) {
		if (handlList.contains(handler))
			handlList.remove(handler);
	}
	
	@Override
	protected void handleMessageFromServer(byte[] msg) {
		String str = new String (msg);
		
		Iterator<HandlerClientIF> itr = handlList.iterator();
		while(itr.hasNext()) {
			HandlerClientIF handle = (HandlerClientIF) itr.next();
			handle.OnMessageReceived(str);
		}
	}
	
	protected void connectionClosed() {
		Iterator<HandlerClientIF> itr = handlList.iterator();
		while(itr.hasNext()) {
			HandlerClientIF handle = (HandlerClientIF) itr.next();
			handle.OnConnectionClosed();
		}
	}
	
	protected void connectionEstablished() {
		Iterator<HandlerClientIF> itr = handlList.iterator();
		while(itr.hasNext()) {
			HandlerClientIF handle = (HandlerClientIF) itr.next();
			handle.OnConnectionEstablished();
		}
	}
	
	protected void connectionException(Exception exception) {
		Iterator<HandlerClientIF> itr = handlList.iterator();
		while(itr.hasNext()) {
			HandlerClientIF handle = (HandlerClientIF) itr.next();
			handle.OnConnectionException(exception);
		}
	}
}
